<template>
  <div class="amap-picker">
    <!-- 搜索框：仅编辑模式显示 -->
    <div v-if="isEdit" class="search-box">
      <el-select
          v-model="selectedPoi"
          filterable
          remote
          clearable
          placeholder="搜索地点"
          :remote-method="handleSearch"
          :loading="searchLoading"
          @change="handleSelect"
          style="width: 240px;"
      >
        <el-option
            v-for="poi in searchResults"
            :key="poi.id"
            :label="poi.name"
            :value="poi"
        >
          <div class="poi-option">
            <div class="poi-name">{{ poi.name }}</div>
            <div class="poi-address">{{ poi.address }}</div>
          </div>
        </el-option>
      </el-select>
    </div>

    <div id="amap-container" class="map"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, defineEmits, defineProps } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: { // 当前坐标
    type: Array,
    default: () => [116.397428, 39.90923]
  },
  zoom: { type: Number, default: 13 },
  mode: { type: String, default: 'view' } // "view" or "edit"
})

const emit = defineEmits(['update:modelValue'])

const map = ref(null)
const marker = ref(null)
const placeSearch = ref(null)

const isEdit = ref(props.mode === 'edit')
const searchResults = ref([])
const selectedPoi = ref(null)
const searchLoading = ref(false)

onMounted(async () => {
  await initMap()
})

async function initMap() {
  const AMap = await AMapLoader.load({
    key: import.meta.env.VITE_API_AMAP_KEY,
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.PlaceSearch']
  })

  map.value = new AMap.Map('amap-container', {
    zoom: props.zoom,
    center: props.modelValue
  })

  marker.value = createMarker(AMap, props.modelValue)

  if (isEdit.value) {
    map.value.on('click', (e) => {
      const position = [e.lnglat.lng, e.lnglat.lat]
      updateMarker(position)
    })

    marker.value.setDraggable(true)
    marker.value.on('dragend', (e) => {
      const position = [e.lnglat.lng, e.lnglat.lat]
      emit('update:modelValue', position)
    })

    AMap.plugin(['AMap.PlaceSearch'], () => {
      placeSearch.value = new AMap.PlaceSearch({
        pageSize: 10,
        citylimit: false
      })
    })
  }

  setTimeout(() => {
    map.value.setFitView([marker.value])
  }, 300)

}

// 搜索地点（远程 el-select 调用）
function handleSearch(query) {
  if (!placeSearch.value || !query) {
    searchResults.value = []
    return
  }
  searchLoading.value = true
  placeSearch.value.search(query, (status, result) => {
    searchLoading.value = false
    if (status === 'complete' && result.poiList?.pois?.length) {
      searchResults.value = result.poiList.pois
    } else {
      searchResults.value = []
      ElMessage.warning('未找到相关地点')
    }
  })
}

// 选中地点后定位
function handleSelect(poi) {
  if (!poi || !poi.location) return
  const pos = [poi.location.lng, poi.location.lat]
  updateMarker(pos)
  map.value.setCenter(pos)
  map.value.setZoom(12)
}

// 创建标记点
function createMarker(AMap, position) {
  return new AMap.Marker({
    position,
    map: map.value,
    icon: new AMap.Icon({
      size: new AMap.Size(18, 34),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      imageSize: new AMap.Size(18, 34)
    }),
    offset: new AMap.Pixel(-9, -34)
  })
}

// 更新标记点
function updateMarker(position) {
  if (!marker.value) return
  marker.value.setPosition(position)
  emit('update:modelValue', position)
}

watch(() => props.modelValue, (val) => {
  if (map.value && marker.value) {
    marker.value.setPosition(val)
    map.value.setCenter(val)
  }
})

watch(() => props.mode, (val) => {
  isEdit.value = val === 'edit'
  if (marker.value) marker.value.setDraggable(isEdit.value)
})
</script>

<style scoped>
.amap-picker {
  position: relative;
  width: 100%;
  height: 100%;

}


.map {
  width: 100%;
  height: 100%;
}

.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  background: #fff;
  padding: 6px 8px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.poi-option {
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-items: center;
}

.poi-name {
  font-weight: 500;
  color: #333;
}

.poi-address {
  font-size: 12px;
  color: #888;
}
</style>
